import { ref, reactive, onUnmounted } from 'vue'

export function useSystemStatus() {
  // 响应式状态
  const systemStatus = reactive({
    uptime: 0,
    memory: {
      used: 0,
      total: 100,
      percentage: 0
    },
    cpu: {
      usage: 0
    },
    devices: {
      total: 0,
      online: 0,
      offline: 0,
      error: 0
    },
    mqtt: {
      connected: false,
      lastPublish: null,
      messagesSent: 0,
      messagesFailed: 0
    },
    dataCollection: {
      totalPoints: 0,
      successRate: 0,
      lastCollection: null
    },
    dataPoints: []
  })

  const connected = ref(false)
  const reconnectTimer = ref(null)
  let ws = null

  // WebSocket连接
  const connectWebSocket = () => {
    // 首先尝试获取初始状态
    fetchSystemStatus().catch(console.error)
    
    // 设置定时获取状态（作为WebSocket的后备方案）
    const statusInterval = setInterval(() => {
      if (!connected.value) {
        fetchSystemStatus().catch(console.error)
      }
    }, 5000)
    
    try {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.hostname}:${window.location.port || 9527}/ws`
      
      ws = new WebSocket(wsUrl)
      
      ws.onopen = () => {
        console.log('WebSocket连接成功')
        connected.value = true
        clearTimeout(reconnectTimer.value)
        clearInterval(statusInterval)
      }
      
      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          handleWebSocketMessage(data)
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }
      
      ws.onclose = () => {
        console.log('WebSocket连接断开，使用轮询模式')
        connected.value = false
        // 不自动重连WebSocket，而是继续使用HTTP轮询
      }
      
      ws.onerror = (error) => {
        console.log('WebSocket不可用，使用HTTP轮询模式')
        connected.value = false
      }
    } catch (error) {
      console.log('WebSocket不可用，使用HTTP轮询模式')
      // 不重试WebSocket连接，依赖HTTP轮询
    }
  }

  // 处理WebSocket消息
  const handleWebSocketMessage = (data) => {
    switch (data.type) {
      case 'system_status':
        Object.assign(systemStatus, data.data)
        break
      
      case 'device_status':
        updateDeviceStatus(data.data)
        break
        
      case 'mqtt_status':
        Object.assign(systemStatus.mqtt, data.data)
        break

      case 'data_points':
        if (Array.isArray(data.data)) {
          systemStatus.dataPoints = data.data
        }
        break
        
      default:
        console.log('收到未知类型消息:', data)
    }
  }

  // 更新设备状态
  const updateDeviceStatus = (deviceData) => {
    // 根据设备状态更新统计数据
    // TODO: 实现设备状态更新逻辑
  }

  // 断开WebSocket连接
  const disconnectWebSocket = () => {
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value)
      reconnectTimer.value = null
    }
    
    if (ws) {
      ws.close()
      ws = null
    }
    
    connected.value = false
  }

  // 获取系统状态
  const fetchSystemStatus = async () => {
    try {
      const response = await fetch('/api/status')
      if (response.ok) {
        const data = await response.json()
        Object.assign(systemStatus, data)
        if (!Array.isArray(systemStatus.dataPoints)) {
          systemStatus.dataPoints = []
        }
        return data
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    } catch (error) {
      console.error('获取系统状态失败:', error)
      throw error
    }
  }

  // 格式化运行时间
  const formatUptime = (seconds) => {
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    
    if (days > 0) {
      return `${days}天 ${hours}小时 ${minutes}分钟`
    } else if (hours > 0) {
      return `${hours}小时 ${minutes}分钟`
    } else {
      return `${minutes}分钟`
    }
  }

  // 格式化内存大小
  const formatMemory = (bytes) => {
    const units = ['B', 'KB', 'MB', 'GB']
    let size = bytes
    let unitIndex = 0
    
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024
      unitIndex++
    }
    
    return `${size.toFixed(1)} ${units[unitIndex]}`
  }

  const resolveTimestamp = (input) => {
    if (input === null || input === undefined) return null
    if (typeof input === 'number') {
      if (input <= 0) return null
      return input > 1e12 ? input : input * 1000
    }
    if (typeof input === 'string') {
      const trimmed = input.trim()
      if (!trimmed) return null
      const numeric = Number(trimmed)
      if (!Number.isNaN(numeric)) {
        if (numeric <= 0) return null
        return numeric > 1e12 ? numeric : numeric * 1000
      }
      const parsed = Date.parse(trimmed)
      if (!Number.isNaN(parsed)) {
        return parsed
      }
    }
    return null
  }

  const formatTime = (timestamp) => {
    const normalized = resolveTimestamp(timestamp)
    if (normalized === null) return '--'
    const date = new Date(normalized)
    if (Number.isNaN(date.getTime())) return '--'
    return date.toLocaleString()
  }

  // 清理资源
  onUnmounted(() => {
    disconnectWebSocket()
  })

  return {
    systemStatus,
    connected,
    connectWebSocket,
    disconnectWebSocket,
    fetchSystemStatus,
    formatUptime,
    formatMemory,
    formatTime
  }
}
